﻿package com.game.manager
{
	import com.dusk.game.Logger;
	
	import flash.utils.Dictionary;
	
	public class EventManager
	{
		
		public function EventManager()
		{
			listenMap = new Dictionary();
		}
		
		private static var _instance:EventManager;
		
		public static function getIns():EventManager
		{
			if (!_instance)
			{
				_instance = new EventManager();
			}
			return _instance;
		}
		
		private var listenMap:Dictionary;
		
		public function registerListen(name:String,func:Function = null):void
		{
			if(func == null)
			{
				return;
			}
			if(listenMap[name] == undefined)
			{
				listenMap[name] = new Vector.<Function>;
			}
			(listenMap[name] as Vector.<Function>).push(func);
		}
		
		public function hasListen(name:String):Boolean
		{
			return listenMap[name] != undefined;
		}
		
		public function removeListen(name:String,func:Function = null):void
		{
			if(func == null)
			{
				if(listenMap[name] != undefined)
				{
					while((listenMap[name] as Vector.<Function>).length > 0)
					{
						(listenMap[name] as Vector.<Function>).pop();
					}
				}
				delete listenMap[name];
			}
			else
			{
				if(listenMap[name] == undefined)
				{
					return;
				}
				if((listenMap[name] as Vector.<Function>).indexOf(func) != -1)
				{
					(listenMap[name] as Vector.<Function>).splice((listenMap[name] as Vector.<Function>).indexOf(func),1);
				}
			}
		}
		
		public function dispatchEvent(name:String,data:Object = null):void
		{
			if(listenMap[name] == undefined)
			{
				return;
			}
			var idx:int = (listenMap[name] as Vector.<Function>).length;
			var func:Function;
			while(idx)
			{
				func = (listenMap[name] as Vector.<Function>)[--idx];
				if(data)
				{
					func.call(null,data);
				}
				else
				{
					func.call(null);
				}
			}
		}
		
		public function removeAll():void
		{
			for(var item:String in listenMap)
			{
				removeListen(item);
			}
			listenMap = new Dictionary();
		}
		
		public function traceListenerNum():void
		{
			for(var item:String in listenMap)
			{
				var total:int = 0;
				if(listenMap[item] != undefined)
				{
					total += listenMap[item].length;
				}
			}
			Logger.log(total.toString());
		}
	}
}